package com.example.filetransfer.gui;

import com.example.filetransfer.client.FileTransferClient;
import com.example.filetransfer.model.Message;
import com.example.filetransfer.util.Base64Util;
import com.example.filetransfer.util.VersionChecker;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class FileTransferApp extends JFrame {
    private static final AtomicInteger clientCounter = new AtomicInteger(1);
    private final int clientId;
    private FileTransferClient client;
    private JTextArea messageArea;
    private JTextField hostField;
    private JTextField portField;
    private JTextField messageField;
    private JButton connectButton;
    private JButton disconnectButton;
    private JButton sendButton;
    private JButton uploadButton;
    private JButton historyButton;
    private JLabel statusLabel;
    
    // 线程池
    private final ExecutorService executorService = Executors.newCachedThreadPool();

    public FileTransferApp() {
        this.clientId = clientCounter.getAndIncrement();
        setTitle("文件传输客户端 #" + clientId);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(600, 500);
        setLocationRelativeTo(null);

        // 检查版本更新
        checkVersion();

        // 创建主面板
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 创建顶部控制面板
        JPanel controlPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);

        // 连接设置
        gbc.gridx = 0;
        gbc.gridy = 0;
        controlPanel.add(new JLabel("主机地址:"), gbc);

        gbc.gridx = 1;
        hostField = new JTextField("localhost", 10);
        controlPanel.add(hostField, gbc);

        gbc.gridx = 2;
        controlPanel.add(new JLabel("端口:"), gbc);

        gbc.gridx = 3;
        portField = new JTextField("9999", 5);
        controlPanel.add(portField, gbc);

        // 按钮
        gbc.gridx = 4;
        connectButton = new JButton("连接");
        controlPanel.add(connectButton, gbc);

        gbc.gridx = 5;
        disconnectButton = new JButton("断开");
        disconnectButton.setEnabled(false);
        controlPanel.add(disconnectButton, gbc);

        gbc.gridx = 6;
        historyButton = new JButton("历史记录");
        historyButton.setEnabled(false);
        controlPanel.add(historyButton, gbc);

        // 状态标签
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.gridwidth = 7;
        statusLabel = new JLabel("状态: 未连接");
        controlPanel.add(statusLabel, gbc);

        mainPanel.add(controlPanel, BorderLayout.NORTH);

        // 创建消息区域
        messageArea = new JTextArea();
        messageArea.setEditable(false);
        messageArea.setLineWrap(true);
        messageArea.setWrapStyleWord(true);
        JScrollPane scrollPane = new JScrollPane(messageArea);
        mainPanel.add(scrollPane, BorderLayout.CENTER);

        // 创建底部发送区域
        JPanel bottomPanel = new JPanel(new BorderLayout(5, 5));

        // 消息输入
        JPanel messagePanel = new JPanel(new BorderLayout(5, 0));
        messageField = new JTextField();
        messageField.setPreferredSize(new Dimension(0, 30));
        sendButton = new JButton("发送");
        sendButton.setEnabled(false);
        messagePanel.add(messageField, BorderLayout.CENTER);
        messagePanel.add(sendButton, BorderLayout.EAST);

        // 文件上传按钮
        uploadButton = new JButton("上传文件");
        uploadButton.setEnabled(false);

        bottomPanel.add(messagePanel, BorderLayout.CENTER);
        bottomPanel.add(uploadButton, BorderLayout.SOUTH);

        mainPanel.add(bottomPanel, BorderLayout.SOUTH);

        // 设置事件处理
        connectButton.addActionListener(e -> connect());
        disconnectButton.addActionListener(e -> disconnect());
        sendButton.addActionListener(e -> sendMessage());
        uploadButton.addActionListener(e -> uploadFile());
        historyButton.addActionListener(e -> showHistory());
        messageField.addActionListener(e -> sendMessage());

        // 窗口关闭事件
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                disconnect();
                executorService.shutdown();
            }
        });

        add(mainPanel);
    }

    private void showHistory() {
        if (client != null) {
            executorService.submit(() -> {
                try {
                    List<Message> messages = client.getRecentMessages(50);
                    SwingUtilities.invokeLater(() -> {
                        messageArea.setText("");
                        for (Message msg : messages) {
                            String timestamp = msg.getTimestamp().format(java.time.format.DateTimeFormatter.ofPattern("HH:mm:ss"));
                            String type = msg.getType() == Message.MessageType.FILE ? "[文件]" : "[消息]";
                            messageArea.append(String.format("[%s] %s [%s] %s\n",
                                timestamp, type, msg.getSender(), msg.getContent()));
                        }
                        messageArea.setCaretPosition(messageArea.getDocument().getLength());
                    });
                } catch (Exception e) {
                    showError("获取历史记录失败: " + e.getMessage());
                }
            });
        }
    }

    private void checkVersion() {
        executorService.submit(() -> {
            try {
                if (VersionChecker.checkForUpdates()) {
                    SwingUtilities.invokeLater(() -> {
                        int choice = JOptionPane.showConfirmDialog(
                            this,
                            "发现新版本，是否立即更新？",
                            "版本更新",
                            JOptionPane.YES_NO_OPTION
                        );
                        
                        if (choice == JOptionPane.YES_OPTION) {
                            if (VersionChecker.downloadNewVersion()) {
                                System.exit(0);
                            } else {
                                JOptionPane.showMessageDialog(
                                    this,
                                    "更新失败，请稍后重试",
                                    "更新失败",
                                    JOptionPane.ERROR_MESSAGE
                                );
                            }
                        }
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    private void connect() {
        executorService.submit(() -> {
            try {
                String host = hostField.getText();
                int port = Integer.parseInt(portField.getText());
                client = new FileTransferClient(host, port);
                client.setMessageHandler(this::logMessage);
                client.connect();

                SwingUtilities.invokeLater(() -> {
                    connectButton.setEnabled(false);
                    disconnectButton.setEnabled(true);
                    sendButton.setEnabled(true);
                    uploadButton.setEnabled(true);
                    historyButton.setEnabled(true);
                    hostField.setEnabled(false);
                    portField.setEnabled(false);
                    statusLabel.setText("状态: 已连接");
                });
            } catch (NumberFormatException e) {
                showError("端口号必须是有效的数字");
            } catch (Exception e) {
                showError("连接失败: " + e.getMessage());
            }
        });
    }

    private void disconnect() {
        if (client != null) {
            executorService.submit(() -> {
                try {
                    client.disconnect();
                    SwingUtilities.invokeLater(() -> {
                        connectButton.setEnabled(true);
                        disconnectButton.setEnabled(false);
                        sendButton.setEnabled(false);
                        uploadButton.setEnabled(false);
                        historyButton.setEnabled(false);
                        hostField.setEnabled(true);
                        portField.setEnabled(true);
                        statusLabel.setText("状态: 未连接");
                    });
                } catch (Exception e) {
                    showError("断开连接失败: " + e.getMessage());
                }
            });
        }
    }

    private void sendMessage() {
        String message = messageField.getText().trim();
        if (!message.isEmpty() && client != null) {
            executorService.submit(() -> {
                try {
                    client.sendMessage(message);
                    SwingUtilities.invokeLater(() -> messageField.setText(""));
                } catch (Exception e) {
                    showError("发送消息失败: " + e.getMessage());
                }
            });
        }
    }

    private void uploadFile() {
        if (client != null) {
            executorService.submit(() -> {
                try {
                    JFileChooser fileChooser = new JFileChooser();
                    fileChooser.setDialogTitle("选择要上传的文件");
                    int result = fileChooser.showOpenDialog(this);
                    if (result == JFileChooser.APPROVE_OPTION) {
                        File file = fileChooser.getSelectedFile();
                        String encodedFile = Base64Util.encodeFile(file);
                        client.uploadFile(encodedFile, file.getName());
                    }
                } catch (Exception e) {
                    showError("上传文件失败: " + e.getMessage());
                }
            });
        }
    }

    private void logMessage(String message) {
        SwingUtilities.invokeLater(() -> {
            String timestamp = java.time.LocalTime.now().format(java.time.format.DateTimeFormatter.ofPattern("HH:mm:ss"));
            messageArea.append(String.format("[%s] [%d] %s\n", timestamp, clientId, message));
            messageArea.setCaretPosition(messageArea.getDocument().getLength());
        });
    }

    private void showError(String message) {
        SwingUtilities.invokeLater(() -> {
            JOptionPane.showMessageDialog(this,
                    message,
                    "错误",
                    JOptionPane.ERROR_MESSAGE);
        });
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            FileTransferApp gui = new FileTransferApp();
            gui.setVisible(true);
        });
    }
} 